package com.lzh.runke.core.handler;

import com.lzh.runke.core.utils.JsonUtil;
import com.lzh.runke.core.entity.FileInfo;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;
import org.springframework.util.ObjectUtils;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @Description:
 * @Author: LiuZiHao
 * @Date: 2022/6/30 11:02
 */
@MappedJdbcTypes(JdbcType.VARCHAR)
@MappedTypes(value = FileInfo.class)
public class FileInfoTypeHandler extends BaseTypeHandler<FileInfo> {
    @Override
    public void setNonNullParameter(PreparedStatement preparedStatement, int i, FileInfo fileInfo, JdbcType jdbcType) throws SQLException {
        if (ObjectUtils.isEmpty(fileInfo)) {
            return;
        }
        String s = JsonUtil.stringify(fileInfo);
        preparedStatement.setString(i, s);
    }

    @Override
    public FileInfo getNullableResult(ResultSet resultSet, String s) throws SQLException {
        return this.convert(resultSet.getString(s));
    }

    @Override
    public FileInfo getNullableResult(ResultSet resultSet, int i) throws SQLException {
        return this.convert(resultSet.getString(i));
    }

    @Override
    public FileInfo getNullableResult(CallableStatement callableStatement, int i) throws SQLException {
        return this.convert(callableStatement.getString(i));
    }

    private FileInfo convert(String s) {
        if (ObjectUtils.isEmpty(s)) {
            return null;
        }
        return JsonUtil.parse(s, FileInfo.class);
    }
}
